package com.javafactroy.kunlong.bip.icp.common.handler;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.net.BindException;

//@RestControllerAdvice //@ControllerAdvice 对应 @Controller
public class ExceptionDealHandler {

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(IllegalStateException.class)
    public Object notFount(IllegalStateException e)
    {
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
        {
            throw e;
        }

        return HttpStatus.ACCEPTED;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object doSomethings(MethodArgumentNotValidException e){
        return HttpStatus.ACCEPTED;
    }

    @ExceptionHandler(BindException.class)
    public Object bindError(BindException bind){
        return HttpStatus.ACCEPTED;
    }

    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handleConstraintViolationException(ConstraintViolationException ex) {
        return HttpStatus.ACCEPTED;
    }

    @ExceptionHandler({Exception.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object allError(Exception ex) {
        return HttpStatus.ACCEPTED;
    }
}